/**
 * $id$
 */
package org.ishequ.miduo;

import java.util.ArrayList;
import org.ishequ.miduo.R;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * The adapter for app list
 */
public class AppListAdapter extends BaseAdapter {
	
	private ArrayList<AppItemGroup> appGroups;
	
	private Activity activity;
	
	public AppListAdapter(Activity activity, ArrayList<AppItemGroup> appGroups) {
		super();
		this.activity = activity;
		this.appGroups = appGroups;
	}

	@Override
	public int getCount() {
		if(appGroups != null) {
			return appGroups.size();
		}
		return 0;
	}

	@Override
	public Object getItem(int position) {
		if(appGroups != null && position >= 0 && position < appGroups.size()) {
			return appGroups.get(position);
		}
		return null;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		if(appGroups != null && position >= 0 && position < appGroups.size()) {
			//设置title
			AppItemGroup group = appGroups.get(position);
			LinearLayout apiItemGroup = 
					(LinearLayout)LayoutInflater.from(parent.getContext())
						.inflate(R.layout.app_item_group, null);
			View titleView = LayoutInflater.from(activity).inflate(R.layout.app_list_item, null); 
			TextView titleGroupTitle = (TextView) titleView.findViewById(R.id.app_group_title);
			View infoView = (View)titleView.findViewById(R.id.app_info);
			infoView.setVisibility(View.GONE);
			titleGroupTitle.setText(group.getTitle());
			apiItemGroup.addView(titleView);
			//添加子项
			ArrayList<AppItem> appItems = group.getAppItems();
			for(final AppItem item : appItems) {
				View itemView = LayoutInflater.from(activity).inflate(R.layout.app_list_item, null); 
				TextView groupTitle = (TextView) itemView.findViewById(R.id.app_group_title);
				TextView appLabel = (TextView) itemView.findViewById(R.id.app_label);
				TextView appName = (TextView) itemView.findViewById(R.id.app_name);
				ImageView logo = (ImageView) itemView.findViewById(R.id.app_logo);
				logo.setImageResource(item.getLogoId());
				appLabel.setText(item.getLabel());
				appName.setText(item.getName());
				groupTitle.setVisibility(View.GONE);
				itemView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						AppInvoker.invoke(activity, item.getLabel());
						activity.finish();
					}
				});
				apiItemGroup.addView(itemView);
			}
			
			convertView = apiItemGroup;
		}
		return convertView;
	}
	
}
